
import { Heading } from "@tiptap/extension-heading";
import { nanoid } from "nanoid";
import { CellSelection } from "prosemirror-tables";
import Image from "@tiptap/extension-image";
import Table from "@tiptap/extension-table";
import TextAlign from "@tiptap/extension-text-align";
import TableCell from "@tiptap/extension-table-cell";
import { Markdown } from "tiptap-markdown";
import TextStyle from "@tiptap/extension-text-style";
import Paragraph from '@tiptap/extension-paragraph'
import { Extension } from "@tiptap/core";

const markDown =   Markdown.configure({
    html: true, // 禁止HTML标签
    breaks: true, // 将换行符转换为<br>
  })
// 表格拖拽
const TableCellMerge = {
    addCommands() {
      return {
        mergeCells:
          () =>
          ({ tr, dispatch }) => {
            const selection = tr.selection;
            const cells = this.getSelectedCells(selection);

            if (!cells || cells.cells.length < 2) return false;

            const firstCell = cells.cells[0];
            const mergedAttrs = {
              ...firstCell.node.attrs,
              colspan: cells.cells.length,
              rowspan: 1,
            };

            cells.cells.slice(1).forEach((cell) => {
              tr.delete(cell.pos - 1, cell.pos);
            });

            tr.setNodeMarkup(firstCell.pos, null, mergedAttrs);

            if (dispatch) tr.setSelection(selection);
            return true;
          },
        splitCell:
          () =>
          ({ tr }) => {
            // 简化拆分逻辑（完整实现需要约100行代码）
            const { selection } = tr;
            if (!(selection instanceof CellSelection)) return false;

            const cell = selection.$anchorCell;
            const attrs = cell.node.attrs;

            if (attrs.colspan === 1 && attrs.rowspan === 1) return false;

            tr.setNodeMarkup(cell.pos, null, {
              ...attrs,
              colspan: 1,
              rowspan: 1,
            });
            return true;
          },
      };
    },
};
// 给段落赋id 为了跳转功能
const HeadingWithId = Heading.extend({
    addAttributes() {
      return {
        id: {
          default: null,
          parseHTML: (element) => element.id || `heading-${nanoid(8)}`,
          renderHTML: (attributes) => {
            return{
              id: attributes.id || `heading-${nanoid(8)}`,
              class:`list-level${attributes.level}`
            }
          },
          // 关键：保持属性更新
          keepOnSplit: true,
        },
        fontSize: {
          default: null,
          parseHTML: (element) => element.style.fontSize,
          renderHTML: (attributes) => ({
            style: `font-size: ${attributes.fontSize}`,
          }),
        },
      };
    },
  }).configure({
    levels: [1,2, 3, 4,5,6,7],
  });
//  Image 配置为以下内容
const CustomImage = Image.extend({
    addAttributes() {
      return {
        // 核心修复：完整保留所有必要属性
        src: {
          default: null,
          parseHTML: (e) => e.getAttribute("src"),
        },
        alt: {
          default: null,
          parseHTML: (e) => e.getAttribute("alt"),
        },
        title: {
          default: null,
          parseHTML: (e) => e.getAttribute("title"),
        },
        style: {
          default: null,
          parseHTML: (e) => e.getAttribute("style"),
        },
        width: {
          default: null,
          parseHTML: (element) => element.style.width || null,
          renderHTML: (attributes) => ({
            style: `width: ${attributes.width}; max-width: 80%; cursor: move;`,
          }),
        },
        height: {
          default: null,
          parseHTML: (element) => element.style.height || null,
          renderHTML: (attributes) => ({
            style: `height: ${attributes.height};`,
          }),
        },
        align: {
          default: "center",
          parseHTML: (element) =>
            element.parentElement.style.textAlign || "center",
        },
      };
    },
  }).configure({
    inline: true,
    allowBase64: true, // 明确允许 Base64
    HTMLAttributes: {
      class: "editor-image resizable-image float-image",
      // 保留所有 HTML 属性
      style: null,
      width: null,
      height: null,
    },
  });
// 表格拓展
  const CustomTable = Table.extend({
    addAttributes() {
      return {
        ...this.parent(),
        align: {
          default: "left",
          parseHTML: (element) => element.style.textAlign || "left",
          renderHTML: (attributes) => ({
            style: `text-align: ${attributes.align}`,
          }),
        },
      };
    },
  }).configure({
    resizable: true,
    handleWidth: 6,
    HTMLAttributes: {
      class: "doc-table",
    },
  });
// 文字样式
const textAlign =   TextAlign.configure({
    types: ["heading", "paragraph", "image", "table"],
    alignments: ["left", "center", "right"], // 支持的对齐方式
  }).extend({
    addOptions() {
      return {
        ...this.parent?.(),
        types: ["heading", "paragraph", "customDiv"], // 添加自定义节点类型
      };
    },
  });
// 表格单元格
const tableCell = TableCell.extend({
    addAttributes() {
      return {
        ...this.parent(),
        textAlign: {
          default: "left",
          parseHTML: (element) => {
            element.style.textAlign;
          },
          renderHTML: (attributes) => ({
            style: `text-align: ${attributes.textAlign}`,
          }),
          style: {
            parseHTML: element => element.style.textAlign,
            renderHTML: () => ({}) // 禁用单元格单独对齐
          }
        },
      };
    },
  })

  // 自定义表格对齐扩展
const AlignableTable = Table
  .configure({
    resizable: true,
    handleWidth: 6,
    HTMLAttributes: {
      class: "doc-table123",
    },
    allowTableNodeSelection: true,
  }).extend({
    addAttributes() {
      return {
        align: {
          default: 'center',
          parseHTML: element => element.style.align || 'center',
          renderHTML: attributes => ({
            style: `text-align: ${attributes.align}; margin: 12px 0;`
          })
        }
      }
    }
  });
  
  const  textStyle =  TextStyle.extend({
    addAttributes() {
      return {
        ...this.parent?.() || {},
        fontSize: {
          default: null,
          parseHTML: element => {
            const size = element.style.fontSize
            if (size && size.endsWith('pt')) {
              return Math.round(parseFloat(size) * 1.333) // 将磅转换为像素
            }
            return null
          },
          renderHTML: attributes => {
            return attributes.fontSize 
              ? { style: `font-size: ${attributes.fontSize}` } 
              : {}
          }
        },
        fontFamily: {
          default: null,
          parseHTML: element => element.style.fontFamily,
          renderHTML: attributes => {
            return attributes.fontFamily 
              ? { style: `font-family: ${attributes.fontFamily}` } 
              : {}
          }
        }
      }
    },
  })
  const FontSize = Extension.create({
    name: "fontSize",
    addOptions() {
      return {
        types: ["textStyle"], // 作用于文本样式
      };
    },
    addGlobalAttributes() {
      return [
        {
          types: this.options.types,
          attributes: {
            fontSize: {
              default: null,
              parseHTML: (element) => element.style.fontSize,
              renderHTML: (attributes) => ({
                style: `font-size: ${attributes.fontSize}`,
              }),
            },
          },
        },
      ];
    },
    addCommands() {
      return {
        setFontSize:
          (fontSize) =>
          ({ chain }) => {
            return chain().setMark("textStyle", { fontSize }).run();
          },
        unsetFontSize:
          () =>
          ({ chain }) => {
            return chain()
              .setMark("textStyle", { fontSize: null })
              .removeEmptyTextStyle()
              .run();
          },
      };
    },
  });
  const CustomParagraph = Paragraph.extend({
    addAttributes() {
      return {
        fontSize: {
          parseHTML: element => element.style.fontSize?.replace('px', ''),
          renderHTML: attributes => {
            // console.log(attributes.fontSize,'fontSize == >attributes');
            return {style: `font-size: ${attributes?.fontSize || '14'}px`}
          }
        },
        textAlign:{
          parseHTML: element => element.textAlign,
          renderHTML: attributes => {
            // console.log(attributes.textAlign,'textAlign == attributes');
            return {style: `text-align: ${attributes?.textAlign || 'left'}`}
          }
        },
        class:{
          default: "custom-p",
          renderHTML: (attributes) => {
            return {
              class: `${attributes.class}`,
            };
          },
        }
        // fontFamily: {
        //   parseHTML: element => element.style.fontFamily,
        //   renderHTML: attributes => ({
        //     style: `font-family: ${attributes.fontFamily}`
        //   })
        // }
      }
    }
  })
export { 
    TableCellMerge,
    HeadingWithId,
    CustomImage,
    CustomTable,
    textAlign,
    tableCell,
    markDown,
    AlignableTable,
    textStyle,
    CustomParagraph,
    FontSize
}